<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意事件，只允许设置第三级分类参数" type="warning" :closable="false" show-icon>
      </el-alert>
      <!-- 商品选择 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader expand-trigger="hover" clearable v-model="seletCateKeys" :options="CateList" :props="CateProps" @change="handelchange"></el-cascader>
        </el-col>
      </el-row>

      <!-- tab标签页切换区 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisable" @click="adddialogVisible=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableDates" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(i,scope.row)">{{item}}</el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDiaolog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeEditDiaolog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label=" 静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisable" @click="adddialogVisible=true">静态属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableDates" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(i,scope.row)">{{item}}</el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDiaolog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeEditDiaolog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="adddialogVisible" width="50%" @close="adddialogClose">
      <!-- 添加参数对话框 -->
      <el-form :model="addform" :rules="addformRules" ref="addformRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="EditdialogVisible" width="50%" @close="EditdialogClose">
      <!-- 添加参数对话框 -->
      <el-form :model="Editform" :rules="EditformRules" ref="EditformRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="Editform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditParams">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      CateList: [],
      // 级联选择框的配置对象
      CateProps: {
        value: 'cat_id',
        label: 'cat_name',
        childrenL: 'children'
      },
      // 级联选择框的双向绑定的对象
      seletCateKeys: [],
      // 被默认激活页签的名称
      activeName: 'many',
      // 动态参数数据
      manyTableDates: [],
      // 静态
      onlyTableDates: [],
      adddialogVisible: false,
      EditdialogVisible: false,
      // 添加参数的数据对象
      addform: {
        attr_name: ''
      },
      Editform: {},
      addformRules: {
        attr_name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ]
      },
      EditformRules: {
        attr_name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    isBtnDisable() {
      if (this.seletCateKeys.length !== 3) {
        return true
      }
      return false
    },
    cateID() {
      if (this.seletCateKeys.length === 3) {
        return this.seletCateKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.CateList = res.data
      console.log(this.CateList)
    },
    handelchange() {
      this.getParamsData()
    },
    // 标签切换事件处理函数
    handleClick() {
      console.log(this.activeName)
      this.getParamsData()
    },
    async getParamsData() {
      // console.log(this.seletCateKeys)
      // 检查当前是否选择三级分类
      if (this.seletCateKeys.length !== 3) {
        this.seletCateKeys = []
        this.onlyTableDates = []
        return
      }
      // 证明选择的是三级分类
      // alert(this.seletCateKeys)
      // 根据所选分类id，和当前面板，获取对应的参数
      const { data: res } = await this.$http(
        `categories/${this.cateID}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表参数失败！')
      }
      console.log(res.data)
      // 循环渲染数组拼接每个字符
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableDates = res.data
      }
      this.onlyTableDates = res.data
    },
    adddialogClose() {
      this.$refs.addformRef.resetFields()
    },
    EditdialogClose() {
      this.$refs.EditformRef.resetFields()
    },
    addParams() {
      this.$refs.addformRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateID}/attributes`,
          {
            attr_name: this.addform.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.adddialogVisible = false
        this.getParamsData()
      })
    },
    // 确认编辑修改
    EditParams() {
      this.$refs.EditformRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateID}/attributes/${this.Editform.attr_id}`,
          {
            attr_name: this.Editform.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
        this.getParamsData()
        this.EditdialogVisible = false
      })
    },
    // 编辑参数对话框
    async showEditDiaolog(attrid) {
      this.EditdialogVisible = true
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes/${attrid}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加参数失败')
      }
      this.Editform = res.data
    },
    // 删除参数项
    async removeEditDiaolog(attrid) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消操作')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateID}/attributes/${attrid}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getParamsData()
      this.EditdialogVisible = false
    },
    async deleteTag(i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(
        `categories/${this.cateID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join('')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加属性失败')
      }
      this.$message.success('添加属性成功')
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 20px;
}
</style>
